<?php
  //Deal with time-outs
  set_time_limit(60);
  ob_start();
  include("../config/config.php");
  include("functions/helpful.php");

  $complete = 0;
  register_shutdown_function('shutdown_timeout',&$complete);

  //The main script
   header ("content-type: application/json");
   $age = CACHE_LIFETIME; //Cache for a day

   $prefix = EXIST_URI.EXIST_DB."?_query=";
   $query =  urlencode(($_GET['q'] ? str_replace("\\","",urldecode($_GET['q'])) : "//iati-activity"));
   $query.= "&_howmany=" .($_GET['howmany'] ? $_GET['howmany'] : "100");
  
  //Caching Routines
  $filename = "/tmp/explorer_json_". md5(str_replace("," , '_',str_replace('/','-',$query))).".json";
  if(file_exists($filename)) {
    $mtime = filemtime($filename);
    $fileage = time() - mtime;
    if ($fileage>$age) {
      $file = file_get_contents($filename);
      print str_replace("\n","",$file);
      ob_flush();
      $complete = 1;
      exit();
    } else {
      //We need to fetch the new file...   
    }
  } 


   //Get the initial data file...

   $data = c_file_get_contents($prefix . $query,86400);

   $xmlDoc = new DOMDocument();
   $xmlDoc->loadXML($data);


   //Need to add some GeoCoding in here...
   geocode(&$xmlDoc);
	
   if($xmlDoc->getElementsByTagName('iati-activity')->item(0)) {
	   $xslDoc = new DOMDocument();
   	   $xslDoc->load("iati-activities-xml-to-json-for-exhibit.xsl");

	   $proc = new XSLTProcessor();
	   $proc->importStylesheet($xslDoc);

	   $outdir = "";

	   $proc->transformToURI($xmlDoc, 'file://'.$outdir.$filename); 
	   $file = str_replace ("\n","",file_get_contents($filename));
	   print $file;
	   $complete = 1;
	   ob_flush();
	   exit();

   } else {
       $complete = 1;
	exError("We could not find IATI data for the country or option you selected"); 
	
   }


// Functions
  function shutdown_timeout($complete) {
    // Generate Error JSON if required. 
    if(!$complete) {
    	ob_end_clean();
	exError("The script could not fetch and process IATI data in the time available. It is possible that some of the process has completed and refreshing this page will allow you to view this data. If you repeatedly see this error, please let us know.");
    }
  }

//Output some error JSON
function exError($error) {
	echo '{ "items": [{	"type":"type-1", "id":"error", "uri":"'. $_SERVER['PHP_SELF'] .'","label":"Error","description":"'.$error.'","start-date":"2000-01-01","end-date":"2010-01-01","activity-status":"Error",'
		.'"collaboration-type":"Try refreshing for data","default-flow-type":"Try refreshing for data","default-aid-type": [ ],"reporting-org":"N/A","participating-org": [],"currency":"NA","total-committments": 0,'
		.'"policy-marker": [ ],"sector": [ ],"sector-amounts": [ ],"components": [],"parents": [ ],"recipient-country":"","recipient-country-code":"","latlng":"","geotype":"Country","timeline":""'
		.'}]}';
}


//This function needs to be updated to work better
function geocode(&$xmlDoc) {
   foreach($xmlDoc->getElementsByTagName('iati-activity') as $activity) {
        foreach($activity->getElementsByTagName('recipient-country') as $country) {
           $code = (string)$country->getAttribute("code");
        }
        $activity->appendChild($xmlDoc->createElement('geocoded-latlng',location($code)));
        $activity->appendChild($xmlDoc->createElement('geocoded-type','Country'));
     }
}


function location($code) {

//Locations from ISO 3166, taken from CIA World Factbook via http://www.maxmind.com/app/country_latlon
$locations = array("AD"=>"42.5,1.5",
"AE"=>"24,54",
"AF"=>"33,65",
"AG"=>"17.05,-61.8",
"AI"=>"18.25,-63.1667",
"AL"=>"41,20",
"AM"=>"40,45",
"AN"=>"12.25,-68.75",
"AO"=>"-12.5,18.5",
"AP"=>"35,105",
"AQ"=>"-90,0",
"AR"=>"-34,-64",
"AS"=>"-14.3333,-170",
"AT"=>"47.3333,13.3333",
"AU"=>"-27,133",
"AW"=>"12.5,-69.9667",
"AZ"=>"40.5,47.5",
"BA"=>"44,18",
"BB"=>"13.1667,-59.5333",
"BD"=>"24,90",
"BE"=>"50.8333,4",
"BF"=>"13,-2",
"BG"=>"43,25",
"BH"=>"26,50.55",
"BI"=>"-3.5,30",
"BJ"=>"9.5,2.25",
"BM"=>"32.3333,-64.75",
"BN"=>"4.5,114.6667",
"BO"=>"-17,-65",
"BR"=>"-10,-55",
"BS"=>"24.25,-76",
"BT"=>"27.5,90.5",
"BV"=>"-54.4333,3.4",
"BW"=>"-22,24",
"BY"=>"53,28",
"BZ"=>"17.25,-88.75",
"CA"=>"60,-95",
"CC"=>"-12.5,96.8333",
"CD"=>"0,25",
"CF"=>"7,21",
"CG"=>"-1,15",
"CH"=>"47,8",
"CI"=>"8,-5",
"CK"=>"-21.2333,-159.7667",
"CL"=>"-30,-71",
"CM"=>"6,12",
"CN"=>"35,105",
"CO"=>"4,-72",
"CR"=>"10,-84",
"CU"=>"21.5,-80",
"CV"=>"16,-24",
"CX"=>"-10.5,105.6667",
"CY"=>"35,33",
"CZ"=>"49.75,15.5",
"DE"=>"51,9",
"DJ"=>"11.5,43",
"DK"=>"56,10",
"DM"=>"15.4167,-61.3333",
"DO"=>"19,-70.6667",
"DZ"=>"28,3",
"EC"=>"-2,-77.5",
"EE"=>"59,26",
"EG"=>"27,30",
"EH"=>"24.5,-13",
"ER"=>"15,39",
"ES"=>"40,-4",
"ET"=>"8,38",
"EU"=>"47,8",
"FI"=>"64,26",
"FJ"=>"-18,175",
"FK"=>"-51.75,-59",
"FM"=>"6.9167,158.25",
"FO"=>"62,-7",
"FR"=>"46,2",
"GA"=>"-1,11.75",
"GB"=>"54,-2",
"GD"=>"12.1167,-61.6667",
"GE"=>"42,43.5",
"GF"=>"4,-53",
"GH"=>"8,-2",
"GI"=>"36.1833,-5.3667",
"GL"=>"72,-40",
"GM"=>"13.4667,-16.5667",
"GN"=>"11,-10",
"GP"=>"16.25,-61.5833",
"GQ"=>"2,10",
"GR"=>"39,22",
"GS"=>"-54.5,-37",
"GT"=>"15.5,-90.25",
"GU"=>"13.4667,144.7833",
"GW"=>"12,-15",
"GY"=>"5,-59",
"HK"=>"22.25,114.1667",
"HM"=>"-53.1,72.5167",
"HN"=>"15,-86.5",
"HR"=>"45.1667,15.5",
"HT"=>"19,-72.4167",
"HU"=>"47,20",
"ID"=>"-5,120",
"IE"=>"53,-8",
"IL"=>"31.5,34.75",
"IN"=>"20,77",
"IO"=>"-6,71.5",
"IQ"=>"33,44",
"IR"=>"32,53",
"IS"=>"65,-18",
"IT"=>"42.8333,12.8333",
"JM"=>"18.25,-77.5",
"JO"=>"31,36",
"JP"=>"36,138",
"KE"=>"1,38",
"KG"=>"41,75",
"KH"=>"13,105",
"KI"=>"1.4167,173",
"KM"=>"-12.1667,44.25",
"KN"=>"17.3333,-62.75",
"KP"=>"40,127",
"KR"=>"37,127.5",
"KW"=>"29.3375,47.6581",
"KY"=>"19.5,-80.5",
"KZ"=>"48,68",
"LA"=>"18,105",
"LB"=>"33.8333,35.8333",
"LC"=>"13.8833,-61.1333",
"LI"=>"47.1667,9.5333",
"LK"=>"7,81",
"LR"=>"6.5,-9.5",
"LS"=>"-29.5,28.5",
"LT"=>"56,24",
"LU"=>"49.75,6.1667",
"LV"=>"57,25",
"LY"=>"25,17",
"MA"=>"32,-5",
"MC"=>"43.7333,7.4",
"MD"=>"47,29",
"ME"=>"42,19",
"MG"=>"-20,47",
"MH"=>"9,168",
"MK"=>"41.8333,22",
"ML"=>"17,-4",
"MM"=>"22,98",
"MN"=>"46,105",
"MO"=>"22.1667,113.55",
"MP"=>"15.2,145.75",
"MQ"=>"14.6667,-61",
"MR"=>"20,-12",
"MS"=>"16.75,-62.2",
"MT"=>"35.8333,14.5833",
"MU"=>"-20.2833,57.55",
"MV"=>"3.25,73",
"MW"=>"-13.5,34",
"MX"=>"23,-102",
"MY"=>"2.5,112.5",
"MZ"=>"-18.25,35",
"NA"=>"-22,17",
"NC"=>"-21.5,165.5",
"NE"=>"16,8",
"NF"=>"-29.0333,167.95",
"NG"=>"10,8",
"NI"=>"13,-85",
"NL"=>"52.5,5.75",
"NO"=>"62,10",
"NP"=>"28,84",
"NR"=>"-0.5333,166.9167",
"NU"=>"-19.0333,-169.8667",
"NZ"=>"-41,174",
"OM"=>"21,57",
"PA"=>"9,-80",
"PE"=>"-10,-76",
"PF"=>"-15,-140",
"PG"=>"-6,147",
"PH"=>"13,122",
"PK"=>"30,70",
"PL"=>"52,20",
"PM"=>"46.8333,-56.3333",
"PR"=>"18.25,-66.5",
"PS"=>"32,35.25",
"PT"=>"39.5,-8",
"PW"=>"7.5,134.5",
"PY"=>"-23,-58",
"QA"=>"25.5,51.25",
"RE"=>"-21.1,55.6",
"RO"=>"46,25",
"RS"=>"44,21",
"RU"=>"60,100",
"RW"=>"-2,30",
"SA"=>"25,45",
"SB"=>"-8,159",
"SC"=>"-4.5833,55.6667",
"SD"=>"15,30",
"SE"=>"62,15",
"SG"=>"1.3667,103.8",
"SH"=>"-15.9333,-5.7",
"SI"=>"46,15",
"SJ"=>"78,20",
"SK"=>"48.6667,19.5",
"SL"=>"8.5,-11.5",
"SM"=>"43.7667,12.4167",
"SN"=>"14,-14",
"SO"=>"10,49",
"SR"=>"4,-56",
"ST"=>"1,7",
"SV"=>"13.8333,-88.9167",
"SY"=>"35,38",
"SZ"=>"-26.5,31.5",
"TC"=>"21.75,-71.5833",
"TD"=>"15,19",
"TF"=>"-43,67",
"TG"=>"8,1.1667",
"TH"=>"15,100",
"TJ"=>"39,71",
"TK"=>"-9,-172",
"TM"=>"40,60",
"TN"=>"34,9",
"TO"=>"-20,-175",
"TR"=>"39,35",
"TT"=>"11,-61",
"TV"=>"-8,178",
"TW"=>"23.5,121",
"TZ"=>"-6,35",
"UA"=>"49,32",
"UG"=>"1,32",
"UM"=>"19.2833,166.6",
"US"=>"38,-97",
"UY"=>"-33,-56",
"UZ"=>"41,64",
"VA"=>"41.9,12.45",
"VC"=>"13.25,-61.2",
"VE"=>"8,-66",
"VG"=>"18.5,-64.5",
"VI"=>"18.3333,-64.8333",
"VN"=>"16,106",
"VU"=>"-16,167",
"WF"=>"-13.3,-176.2",
"WS"=>"-13.5833,-172.3333",
"YE"=>"15,48",
"YT"=>"-12.8333,45.1667",
"ZA"=>"-29,24",
"ZM"=>"-15,30",
"ZW"=>"-20,30");

  return $locations[$code];

}




?>


